import { Router, RouteRecordRaw } from "vue-router";
import { PageEnum } from "@/enums/PageEnum";
import { storage } from "@/utils/storage";
import { useAsyncRouteStoreOutSetup } from "@/store/modules/system/asyncRoute";
import { ErrorPageRoute } from "@/router/base";
import { CURRENT_USER } from "@/store/mutation-types";

/**
 * 路由拦截
 * @param router
 */
export function createRouterGuard(router: Router) {
  // 异步处理routes.
  const asyncRouteStore = useAsyncRouteStoreOutSetup();

  router.beforeEach(async (to, form, next) => {
    window.$loadingBar?.start();
    // 如果是在登录后跳转的是404页面, 则跳转到首页.
    if (
      form.path === PageEnum.BASE_LOGIN &&
      to.name === PageEnum.ERROR_PAGE_NAME
    ) {
      next(PageEnum.BASE_HOME);
      return;
    }
    // 如果接下来要进入登录页面, 无需拦截.
    if (to.path === "/sign-in") {
      next();
      return;
    }

    // TODO 这里备注掉了登录校验.
    // TODO 如果需要用token, 修改这里.
    // 千万不要用cookie里的JSESSIONID做判断, 为了防止xss攻击, JSESSIONID无法通过js读取.
    // const token = store.get(CURRENT_USER);
    //
    // // 如果用户未登录.
    // if (!token) {
    //   // 如果进入的是不需要权限的页面.
    //   if (to.meta.ignoreAuth) {
    //     next();
    //     return;
    //   }
    //   // 否则重定向到登录页面.
    //   if (to.path) {
    //     next({
    //       path: PageEnum.BASE_LOGIN,
    //       replace: true,
    //     });
    //     return;
    //   }
    // }

    const routes: RouteRecordRaw[] =
      (await asyncRouteStore.generateRoutes()) as RouteRecordRaw[];

    // 动态添加可访问路由表
    routes.forEach((item) => {
      router.addRoute(item as unknown as RouteRecordRaw);
    });

    const isErrorPage = router
      .getRoutes()
      .findIndex((item) => item.name === ErrorPageRoute.name);

    if (isErrorPage === -1) {
      router.addRoute(ErrorPageRoute);
    }

    next();
    return;
  });
  router.afterEach(() => {
    window.$loadingBar?.finish();
    return;
  });
}
